package com.lebang.medicalInquiry.controller.sys;



import com.lebang.medicalInquiry.constant.UserConstants;
import com.lebang.medicalInquiry.model.po.SysRole;
import com.lebang.medicalInquiry.model.po.SysUser;
import com.lebang.medicalInquiry.model.vo.SysRoleVo;
import com.lebang.medicalInquiry.response.Callback;
import com.lebang.medicalInquiry.response.JsonData;
import com.lebang.medicalInquiry.service.SysRoleService;
import com.lebang.medicalInquiry.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;
import java.util.HashMap;
import java.util.List;

/**
 * @author zpc
 * @version V1.0
 */
@Api(tags = "【web端】角色权限")
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysUserService userService;

    @RequiresPermissions(value = {"sys:role:get"})
    @ApiOperation("根据关键词查询角色信息")
    @GetMapping("/")
    public JsonData list(
            @ApiParam(name = "roleName", value = "角色名称")
            @RequestParam(name = "roleName", required = false) String roleName,
            @ApiParam(name = "roleKey", value = "角色权限标识")
            @RequestParam(name = "roleKey", required = false) String roleKey,
            @RequestParam(name = "page", defaultValue = "1", required = false) @Min(1) Integer page,
            @RequestParam(name = "limit", defaultValue = "10", required = false) @Min(1) Integer limit) {
        try {
            List<SysRole> list = roleService.selectRoleList(roleName, roleKey, (page - 1) * limit, limit);
            int count = roleService.countRoleList(roleName, roleKey);
            HashMap<Object, Object> map = new HashMap<>();
            map.put("list", list);
            map.put("count", count);

            return Callback.success("200", "成功", map);
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }


    /**
     * 新增保存角色
     */
    @RequiresPermissions(value = {"sys:role:post"})
    @ApiOperation("新增保存角色")
    @PostMapping("/")
    public JsonData addSave(HttpServletRequest servletRequest, @RequestBody SysRoleVo role) {
        try {
            if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
                return Callback.fail("505", "新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
            } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
                return Callback.fail("505", "新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
            }

            roleService.insertRole(role);
            return Callback.success("200", "成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }


    }


    /**
     * 修改保存角色
     */
    @RequiresPermissions(value = {"sys:role:put"})
    @ApiOperation("修改保存角色")
    @PutMapping("/")
    public JsonData editSave(HttpServletRequest servletRequest, @RequestBody SysRoleVo role) {
        try {
            if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
                return Callback.fail("505", "修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
            } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
                return Callback.fail("505", "修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
            }

            roleService.updateRole(role);
            return Callback.success("200", "成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }


    /**
     * 批量删除角色
     */
    @RequiresPermissions(value = {"sys:role:delete"})
    @ApiOperation("批量删除角色")
    @DeleteMapping("/")
    public JsonData remove(@RequestParam(name = "ids", required = false) String ids) {
        try {

            if (-1 == roleService.deleteRoleByIds(ids)) {
                return Callback.fail("606", "删除失败当前角色已被使用");
            }
            return Callback.success("200", "成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }


    /**
     * 查询用户的角色
     */
    @RequiresPermissions(value = {"sys:role:user:post"})
    @ApiOperation("查询用户的角色并反显")
    @PostMapping("/user/{userId}")
    public JsonData getUserRole(@PathVariable("userId") Long userId) {
        try {
            SysUser user = userService.getUser(userId);
            if (user == null) {
                return Callback.fail("606", "当前用户不存在");
            }
            List<SysRole> sysRoles = roleService.selectRolesByUserId(userId);
            return Callback.success("200", "成功", sysRoles);
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions(value = {"sys:role:batch:select:post"})
    @ApiOperation("批量选择用户授权")
    @PostMapping("/batch/select")
    public JsonData selectAuthUserAll(Long roleId, String userIds) {
        try {
            roleService.insertAuthUsers(roleId, userIds);
            return Callback.success("200", "成功");
        } catch (Exception e) {
            return Callback.fail("500", "异常");
        }

    }
}
